﻿using FX_API.Models;
using FX_API.Factory;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace FX_API.Request
{
    public class FXCommonUpdateRequest : FXBasicRequest
    {
        public delegate void HttpResponseHandler(string responseMsg, FXUpdateRequestModel request);
        public HttpResponseHandler httpErrHandler;
        public override string url { get; set; }

        public FXUpdateResponseModel Update(IObjectData objectData, object details = null, bool triggerWorkFlow = false)
        {
            FXUpdateRequestModel requestModel;
            FXUpdateResponseModel responseModel = null;

            url = objectData.dataObjectApiName.EndsWith("__c") ? FenxiangAPI.customizedUpdateURL : FenxiangAPI.presetUpdateURL;

            try
            {
                if (details == null)
                {
                    requestModel = UpdateModelFactory.CreateUpdateModel(objectData, triggerWorkFlow);
                }
                else
                {
                    requestModel = UpdateModelFactory.CreateUpdateModelWithDetails(objectData, details, triggerWorkFlow);
                }

                var response = SendRequest(requestModel);

                if (response.IsSucess != true)
                {
                    httpErrHandler?.Invoke(response.Message, requestModel);
                    return null;
                }

                responseModel = JsonConvert.DeserializeObject<FXUpdateResponseModel>(response.Message);
            }
            catch (Exception ex)
            {
                exceptionHandler?.Invoke(ex);
            }

            return responseModel;
        }
    }
}
